import React, { useEffect, useState, Fragment } from 'react';
import { connect } from 'umi';
import { Card, Form, Button, message, ConfigProvider } from 'antd';
import moment from 'moment';
import { eventTrack } from '@/utils/track';
import { history } from 'umi';
import { formItemLayout } from '@/components/UserForm';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import SlidedTabs from '@/components/SlideTabs';
// import { findCountry } from '@/pages/RecruitManage/PositionManage/part/utils';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageRouter from '@/components/PageRouter/PageRouter';
import { getTempDetail } from '@/services/myRecruit/talentPool';
import pageTabUtil from '@/utils/pageTabUtil';

import InfoFrom from './Components/InfoFrom';
import PlanForm from './Components/PlanForm';
import SendMail from './Components/SendMail';
import { findIdentity } from './dict';
import styles from './TerviewList.less';
// import { getDict } from '@/services/components/userform';
// import { getemployeebyrole } from '@/services/myRecruit/interview';
let a = [];
let b = [];
let clickType = ''; // 控制是普通提交还是附带通知候选人的提交
const AddInterview = ({ loading, dispatch, form, user, ...rags }) => {
    // const interLeader = {};
    // const interViewDict = {};
    const User = user.currentUser; // 登陆人信息
    const [candidate, setCandidate] = useState('');
    const [candidateCode, setCandidateCode] = React.useState();
    const [talentCode, setTalentCode] = React.useState('');
    const [interviewimage, setinterviewimage] = useState('');
    const [tempInfo, setTempInfo] = React.useState({}); // 控制邮件模板类型
    const [mailModel, setMailModel] = React.useState(false); // 控制通知候选人邮件模态框
    // const [clickType, setClickType] = React.useState(''); // 控制是普通提交还是附带通知候选人的提交
    const [count, setCount] = React.useState(1);
    // SlidedTabs
    const [activeKey, setActiveKey] = useState('1');
    // 获取改页面的身份 很多按钮的判断都是根据这个身份去显示
    const dictList = findIdentity(rags.location.query.type);
    const { tabs = [] } = dictList;
    // SlidedTabs
    const getPayload = () => {
        const values = form.getFieldsValue();
        const payload = {
            arrangeCode: '', // 面试安排code （从面试详情页发起时传）
            candidateCode: candidate.candidateCode,
            companyId: candidate.companyId,
            interviewEmployeeCode: values.interviewEmployeeCode,
            interviewLeaderId: values.interviewLeaderId,
            interviewLocation: values.interviewLocation,
            interviewRemark: values.interviewRemark,
            interviewTime: values.time.format(
                `${moment(values.time, 'YYYY-MM-DD').format('YYYY-MM-DD')} ${values.timeValue}:00`
            ),
            interviewType: values.interviewType,
            interviewWay: values.interviewWay
        };
        return payload;
    };
    const getDictData = dictData => {
        a = dictData;
    };
    const getLeaderMsg = leaderMsg => {
        b = leaderMsg;
    };
    const getInfo = () => {
        const values = form.getFieldsValue();
        const dictDataArr = a.filter(item => item.dictValue === values.interviewWay);
        const leaderMsgArr = b.filter(item => item.id === values.interviewLeaderId);
        setTempInfo({
            ...tempInfo,
            interviewWay: dictDataArr.length ? dictDataArr[0].dictName : '',
            interviewTime: values.time
                ? values.time.format(`${moment(values.time, 'YYYY-MM-DD').format('YYYY-MM-DD')} ${values.timeValue}:00`)
                : '',
            interviewLocation: values.interviewLocation,
            recruitMaster: leaderMsgArr.length ? leaderMsgArr[0].employeeName : '',
            recruitMasterMobile: leaderMsgArr.length ? leaderMsgArr[0].mobile : '',
            recruitMasterEmail: leaderMsgArr.length ? leaderMsgArr[0].email : '',
            recruitMasterMobileAreaCode: leaderMsgArr.length ? leaderMsgArr[0].areaCode : ''
        });
        // setClickType('mailSubmit');
        clickType = 'mailSubmit';
        setCount(count + 1);
    };
    const handleSubmit = () => {
        form.validateFields(err => {
            if (!err) {
                dispatch({
                    type: 'interview/savefistinterview',
                    payload: getPayload(),
                    callback: async res => {
                        if (res.code === 10000) {
                            message.success(res.msg);
                            if (clickType === 'submit') {
                                // 埋点
                                history.push({
                                    pathname:
                                        rags.route.name === 'adminaddinterview'
                                            ? '/office/personnelManagement/recruit/interview'
                                            : '/personal/portal/recruit/interview'
                                });
                                eventTrack({
                                    eventName: 'personal_my_recruit_interview_add_submit_click',
                                    eventProps: {
                                        status: 0
                                    }
                                });
                            } else {
                                const result = await getTempDetail({ talentCode });
                                if (result && result.code === 10000) {
                                    setTempInfo({
                                        ...tempInfo,
                                        talentCode,
                                        key: result.data.key,
                                        registerStatus: result.data.registerStatus
                                    });
                                    setMailModel(true);
                                    eventTrack({
                                        eventName: 'personal_my_recruit_interview_add_submitRemind_click',
                                        eventProps: {
                                            status: 0
                                        }
                                    });
                                }
                            }
                        } else {
                            message.error(res.msg);
                        }
                    }
                });
            }
            if (err && clickType === 'submit') {
                eventTrack({
                    eventName: 'personal_my_recruit_interview_add_submit_click',
                    eventProps: {
                        status: 1,
                        error_info: JSON.stringify(err)
                    }
                });
            } else if (err && clickType === 'mailSubmit') {
                eventTrack({
                    eventName: 'personal_my_recruit_interview_add_submitRemind_click',
                    eventProps: {
                        status: 1,
                        error_info: JSON.stringify(err)
                    }
                });
            }
        });
    };

    const handleMailOpen = () => {
        getInfo();
    };
    useEffect(() => {
        if (count > 1) {
            handleSubmit();
        }
    }, [count]);
    const extra = () => (
        <Fragment>
            <Button
                // 埋点
                onClick={async () => {
                    await eventTrack({
                        eventName: 'personal_my_recruit_interview_add_cancel_click',
                        eventProps: {
                            tabs: '我的面试',
                            label: '发起面试-返回'
                        }
                    });
                    pageTabUtil.goBack();
                }}
            >
                返回
            </Button>
            <Button
                // loading={loading.effects['interview/savefistinterview']}
                type="primary"
                style={{ marginLeft: 10 }}
                onClick={e => {
                    e.preventDefault();
                    clickType = 'submit';
                    // setClickType('submit');
                    setCount(count + 1);
                    // handleSubmit();
                    // 埋点
                }}
            >
                提交
            </Button>
            <Button
                type="primary"
                style={{ marginLeft: 10 }}
                onClick={e => {
                    e.preventDefault();
                    handleMailOpen();
                }}
            >
                提交并通知候选人
            </Button>
        </Fragment>
    );
    // 预览面试评分表
    const previewImage = () => {
        dispatch({
            type: 'interview/getinterviewimage',
            payload: {
                postType: candidate.postType
            },
            callback: res => {
                setinterviewimage(res.url);
            }
        });
    };
    // const candidataMap = [];
    // 候选人查询
    const candidateSearch = code => {
        dispatch({
            type: 'interview/getinterviewrecruitinfo',
            payload: {
                arrangeCode: code
            },
            callback: res => {
                // const { postTypeRemark = 'GroupRecruitPostType' } = findCountry(res.companyId);
                form.setFieldsValue({
                    talentName: res.talentName,
                    talentPhone: res.talentPhone,
                    recruitPost: res.recruitPost,
                    departmentName: res.departmentName,
                    postType: res.postType,
                    projectGroup: res.projectGroup,
                    resourceRelation: res.interviewFile,
                    talentAreaCode: res.talentAreaCode,
                    postGradeCode: res.postGradeCode
                });
                setTempInfo({
                    ...tempInfo,
                    candidateName: res.talentName,
                    reviewPost: res.recruitPost,
                    talentEmail: res.talentEmail
                });
                setTalentCode(res.talentCode);
                previewImage();
                setCandidateCode(res.setCandidateCode);
                setCandidate(res);
            }
        });
    };

    useEffect(() => {
        if (rags.location.query.candidateCode) {
            candidateSearch(rags.location.query.candidateCode);
        }
    }, []);
    return (
        <PageHeaderWrapper>
            <PageRouter type="myrecruit" activePath="/personal/portal/recruit/interview">
                <Form layout="horizontal" {...formItemLayout}>
                    <Card
                        bordered={false}
                        title="新增-面试"
                        extra={extra()}
                        style={{ padding: 0, margin: 0 }}
                        headStyle={{ paddingLeft: 40 }}
                        bodyStyle={{ padding: 0 }}
                    >
                        <SlidedTabs
                            cardStyle={{
                                height: 'calc(100vh - 325px)',
                                marginRight: 4,
                                padding: 0
                            }}
                            tabs={tabs}
                            activeKey={activeKey}
                            onChange={key => setActiveKey(key)}
                        >
                            {refs => (
                                <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                                    <div ref={refs[0].ref} className="form-Wrap">
                                        <InfoFrom
                                            form={form}
                                            resourceRelation={candidate.talentFile}
                                            onCandidateSearch={code => {
                                                candidateSearch(code);
                                            }}
                                            candidate={candidate}
                                            dictList={dictList}
                                        />
                                    </div>
                                    <div className={styles.line} />
                                    <div ref={refs[1].ref} className="form-Wrap">
                                        <PlanForm
                                            form={form}
                                            user={User}
                                            dictList={dictList}
                                            candidate={candidate}
                                            getDictData={getDictData}
                                            getLeaderMsg={getLeaderMsg}
                                            interviewimage={interviewimage}
                                        />
                                    </div>
                                </ConfigProvider>
                            )}
                        </SlidedTabs>
                    </Card>
                </Form>
                <SendMail
                    form={form}
                    visible={mailModel}
                    setMailModle={setMailModel}
                    data={{ tempInfo, candidateCode }}
                    onCancel={() => {
                        setMailModel(false);
                    }}
                />
            </PageRouter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ loading, user }) => ({
        user,
        loading
    }))(Form.create()(AddInterview))
);
